<template>
  <div v-loading="tabLoading">
    <el-button type="primary" class="fr" @click="tab6CreateItem" v-permission="'materialInfo.add'">创建</el-button>
    <div class="filter-container">
      <el-select v-model="tab6QueryParams.custom_id" class="filter-item" filterable remote
        :remote-method="tabsixcustomGetlist" placeholder="请选择客户" clearable>
        <el-option v-for="i in tab6CustomOptions" :key="i.id" :label="i.label" :value="i.value"></el-option>
      </el-select>
      <el-select v-model="tab6QueryParams.group_id" class="filter-item" filterable placeholder="请选择工序" clearable>
        <el-option v-for="i in tab6GroupOptions" :key="i.id" :label="i.label" :value="i.value"></el-option>
      </el-select>
      <el-button class="filter-item" type="success" plain @click="tab6Research">查询</el-button>
    </div>
    <z-table :list="tab6List" :tableProps="tab6TableProps" :columns="tab6Columns" @editItem="tab6EditItem"
      @deleteItem="tab6DeleteItem">
      <template v-slot:content="v">
        <span v-if="v.key==='label_name'">
          <a href="#" @click.stop="newLink(v.row['file_list'])" class="text-blue text-bold">{{v.row[v.key]}}</a>
        </span>
        <span v-else>{{v.row[v.key]}}</span>
      </template>
    </z-table>
    <z-pagination :pagination="pagination" :total="total" :page.sync="tab6QueryParams.page"
      :limit.sync="tab6QueryParams.size" @change="paginationschane"></z-pagination>
    <el-dialog :title="tab6Data.id?'编辑':'创建'" :width="tab6FormProps.dialogWidth" :close-on-click-modal="false"
      :visible.sync="tab6EditFormVisible">
      <div style="padding-right: 100px;">
        <z-form :data="tab6Data" :formProps="tab6FormProps" :fields="tab6Fields"></z-form>
        <el-form v-bind="tab6FormProps">
          <el-form-item label="标签字段">
            <el-button v-if="tab6Data.detail && tab6Data.detail.length == 0" style="margin-left: 3px;" type="primary"
              @click="tab6AddDetail()" size="mini" icon="el-icon-plus" circle>
            </el-button>
            <div>
              <el-row :gutter="15" v-for="(d,i) in tab6Data.detail" :key="i" style="margin:0;margin-bottom: 5px;">
                <el-col :span="6">
                  <el-select v-model="d.name" placeholder="视图名称" style="width:100%;">
                    <el-option v-for="i in tab6ViewOptions" :key="i.id" :label="i.label" :value="i.value">
                    </el-option>
                  </el-select>
                </el-col>
                <el-col :span="15">
                  <el-select v-model="d.value" placeholder="选择字段" style="width:100%;" multiple filterable>
                    <el-option v-for="i in tab6FieldOptions(d)" :key="i.id"
                      :label="i.param_value + ' ' + i.param_condition1" :value="i.param_value"></el-option>
                  </el-select>
                </el-col>
                <el-col :span="3">
                  <el-button type="danger" size="mini" icon="el-icon-minus" @click="tab6RemoveDetail(i)" circle>
                  </el-button>
                  <el-button style="margin-left: 3px;" type="primary" @click="tab6AddDetail(i)" size="mini"
                    icon="el-icon-plus" v-show="i == (tab6Data.detail.length - 1)" circle></el-button>
                </el-col>
              </el-row>
            </div>
          </el-form-item>
        </el-form>
        <div class="text-right">
          <el-button @click="tab6EditFormVisible = false">取消</el-button>
          <el-button v-if="!tab6FormProps.disabled" type="primary" @click.native="tab6Submit" :loading="submitLoading">
            确认
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import commonMixin from '@/views/_common/mixin'
import { getToken } from '@/utils/auth'
export default {
  mixins: [commonMixin],
  name: '',
  components: {},
  props: {},
  data() {
    return {
      tabLoading: false,
      submitLoading: false,
      tab6QueryParams: {
        page: 1,
        size: 10,
        cust_id: null,
        group_id: null,
      },
      total: 0,
      tab6CustomOptions: [],
      tab6GroupOptions: [],
      tab6ViewOptions: [],
      tab6List: [],
      tab6TableProps: {
        border: true,
        opsColWith: 80,
        hideOperations: true,
      },
      tab6Columns: [
        { title: '客户编码', key: 'cust_code', width: 120 },
        { title: '客户名称', key: 'cust_name', width: 140 },
        { title: '工序名称', key: 'group_name', width: 140 },
        { title: '标签档名称', key: 'label_name' },
        { title: '标签打印数量', key: 'label_qty', width: 120 },
        { title: '修改人', key: 'modify_user', width: 100 },
        { title: '最后修改', key: 'modify_time', width: 140 },
      ],
      tab6Data: {},
      tab6FormProps: {
        dialogWidth: '70%',
        labelWidth: '140px',
      },
      tab6Fields: [
        {
          title: '客户',
          key: 'cust_id',
          name: 'select',
          span: 16,
          options: [],
          tips: '如果不选，则适用于所有客户',
          props: { clearable: true },
        },
        {
          title: '标签层级',
          key: 'label_level',
          span: 8,
          name: 'select',
          options: [
            { label: '盒标', value: 1 },
            { label: '箱标', value: 2 },
            { label: '栈板', value: 3 },
          ],
        },
        {
          title: '上传label档案',
          key: 'labels',
          name: 'fileUploader',
          span: 24,
          props: {
            limit: 1,
            action: this.$api.fileupload + 'upload',
            onSuccess: this.tab6AfterUpload,
            onRemove: this.tab6OnRemove,
            onPreview: this.tab6OnPreview,
            headers: {
              Authorization: 'Bearer ' + getToken(),
            },
          },
        },
        { title: '标签打印数量', key: 'label_qty', span: 12, name: 'number', props: { min: 1 } },
        {
          title: '工序',
          key: 'group_id',
          name: 'select',
          span: 12,
          options: [],
          tips: '如果不选，则不限制可使用的工序',
          props: {
            clearable: true,
          },
        },
        { title: '备注', key: 'remarks', span: 24, name: 'textarea' },
      ],
      tab6EditFormVisible: false,
    }
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {},
  methods: {
    // 获取客户
    tabsixcustomGetlist(val) {
      this.$request(this.$api.custom + 'getlist', { page: 1, size: 100, queryString: val ? val : '' }).then((r) => {
        this.tab6CustomOptions = r.list.map((i) => ({
          label: `${i.cust_code} ${i.cust_name}`,
          value: i.id,
        }))
        this.$parent.$parent.$parent.setArrayProps(this.tab6Fields, [
          {
            key: 'cust_id',
            options: this.tab6CustomOptions,
          },
        ])
      })
    },
    // 获取工序
    tabsixgetlistbypage(val) {
      this.$request(this.$api.group + 'getlistbypage', { page: 1, size: 100, queryString: val ? val : '' }).then(
        (r) => {
          this.tab6GroupOptions = r.list.map((i) => ({
            label: `${i.group_name}`,
            value: i.id,
          }))
          this.$parent.$parent.$parent.setArrayProps(this.tab6Fields, [
            {
              key: 'group_id',
              options: this.tab6GroupOptions,
            },
          ])
        },
      )
    },
    tab6Init() {
      this.tabsixcustomGetlist()
      this.tabsixgetlistbypage()

      this.$request(this.$api.factor + 'getlist', { page: 1, size: 10, coding_type: 'view' }).then((r) => {
        this.$request(this.$api.param + 'getlist', { page: 1, size: 10, paramType: 'LABEL_VIEW_FIELDS' }).then((r2) => {
          this.tab6ViewOptions = r.list.map((i) => ({
            label: `${i.coding_param} ${i.coding_desc}`,
            value: i.coding_param,
            children: r2.list.filter((j) => j.param_name == i.coding_param),
          }))
          this.$parent.$parent.$parent.setArrayProps(this.tab6Fields, [
            {
              key: 'view',
              options: this.tab6ViewOptions,
            },
          ])
        })
      })
      this.tab6Research()
    },
    tab6Research() {
      this.tab6GetList()
    },
    paginationschane(val) {
      this.tab6QueryParams.size = val.limit
      this.tab6QueryParams.page = val.page
      this.tab6GetList()
    },
    tab6GetList() {
      if (!this.$parent.$parent.$parent.data.id) return
      this.tabLoading = true
      this.tab6QueryParams.sku_id = this.$parent.$parent.$parent.data.id
      this.$request(this.$api.material + 'labelconfig/getlist', this.tab6QueryParams)
        .then((r) => {
          this.tabLoading = false
          this.tab6List = r.list
          this.total = r.total
        })
        .catch(() => {
          this.tabLoading = false
        })
    },
    tab6CreateItem() {
      this.tab6Data = { sku_id: this.$parent.$parent.$parent.data.id, detail: [] }
      this.tab6EditFormVisible = true
    },
    tab6EditItem(v) {
      this.tab6Data = {}
      this.$parent.$parent.$parent.pageLoading = true
      this.$request(this.$api.material + 'labelconfig/getbyid', {
        id: v.id,
      })
        .then((r) => {
          this.$parent.$parent.$parent.pageLoading = false
          this.tab6Data = r
          this.tab6Data.labels = this.tab6Data.label_path
            ? [{ name: this.tab6Data.label_name, url: this.tab6Data.label_path }]
            : []
          this.tab6Data.detail.forEach((i) => {
            i.value = i.value ? i.value.split(',') : []
          })
          this.tab6EditFormVisible = true
        })
        .catch(() => {
          this.$parent.$parent.$parent.pageLoading = false
        })
    },
    tab6DeleteItem(v) {
      this.$confirm('确定要删除这条记录？', '操作确认').then(() => {
        this.$parent.$parent.$parent.pageLoading = true
        this.$request(this.$api.material + 'labelconfig/delete/' + v.id, {}, 'post')
          .then((r) => {
            this.$parent.$parent.$parent.pageLoading = false
            this.$message({
              message: '操作成功',
              type: 'success',
            })
            this.tab6GetList()
          })
          .catch(() => {
            this.$parent.$parent.$parent.pageLoading = false
          })
      })
    },
    tab6Submit() {
      this.submitLoading = true
      let data = _.cloneDeep(this.tab6Data)
      if (data.detail.length > 0) {
        data.detail.forEach((i) => {
          i.value = i.value ? i.value.join(',') : ''
        })
      }
      this.$request(this.$api.material + 'labelconfig/add', data, 'post')
        .then((r) => {
          this.submitLoading = false
          this.$message({
            message: '操作成功',
            type: 'success',
          })
          this.tab6EditFormVisible = false
          this.tab6GetList()
        })
        .catch(() => {
          this.submitLoading = false
        })
    },
    tab6AddDetail(i) {
      i = i || 0
      this.tab6Data.detail.splice(i + 1, 0, {})
    },
    tab6RemoveDetail(i) {
      this.tab6Data.detail.splice(i, 1)
    },
    tab6AfterUpload(r, f, l) {
      this.$message({
        message: '上传成功',
        type: 'success',
      })
      this.tab6Data.label_name = f.name
      this.tab6Data.label_path = r
    },
    tab6OnRemove() {
      this.tab6Data.label_name = ''
      this.tab6Data.label_path = ''
    },
    tab6OnPreview(f) {
      if (f.url) this.newLink(this.$api.baseUrl + f.url)
    },
    tab6FieldOptions(v) {
      let t = this.tab6ViewOptions.find((i) => i.value == v.name)
      return t ? t.children : []
    },
    newLink(val) {
      if (!val.length) {
        return this.$message.warning('此条数据没有上传文件')
      }
      let url = val[0].url
      let a = document.createElement('a')
      a.setAttribute('href', url)
      a.setAttribute('target', '_blank')
      a.click()
      a.remove()
    },
  },
}
</script>

<style lang="less" scoped></style>